<script setup>

import {ref,onMounted} from 'vue';
import {queryAllApi,queryById,addProject,updateProject,deleteProject} from "@/api/nursingproject";
import { ElMessage ,ElMessageBox } from 'element-plus';

const searchService = ref({
  name: "",
  status: "",
});
const serviceList = ref([]);
//定义分页数据
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
const size='default'
const disabled = false
const background = true

const handleSizeChange = (val) => {
console.log(`每页${val}条`)
currentPage.value=1
pageSize.value=val
handleSearch()
}
const handleCurrentChange = (val) => {
  console.log(`当前页: ${val}`)
  currentPage.value = val
  handleSearch()
}
const handleSearch = async () => { 
let result = await queryAllApi(searchService.value.name,searchService.value.status,currentPage.value,pageSize.value)
serviceList.value = result.data.rows
total.value = result.data.total
}

const deleteIds = ref([])
const handleSelectionChange = (selection)=>{
  let idCollection = selection.map((item=>item.id))
  deleteIds.value = idCollection
}
const deleteByIds = async () => { 
  ElMessageBox
  .confirm(
    '你确定要删除吗？','Warning',
    {
      confirmButtonText: 'OK',
      cancelButtonText: 'Cancel',
      type: 'warning',
    })
    .then( async() => {
        let result = await deleteProject(deleteIds.value)
        handleSearch()
        ElMessage.success("删除成功！")
    })
    .catch(() => {
    ElMessage.info('已取消删除')
    })
}
const deleteById = (id) =>{
    deleteIds.value=[id]
    deleteByIds()
}


//新增或者修改弹框
const dialogShow = ref(false)
const tips = ref('')

const formData= ref({
    name:'',
    status:null,
    nursingRequirement:'',
    orderNo:'',
    price:'',
    unit:'',
    image:''
})
const statusList = ref([
    {value:1,name:'启用'},
    {value:0,name:'禁用'},
])

const showDialog = () =>{ 
    dialogShow.value = true
    tips.value = '新增'
    formData.value = {
            name:'',
            status:null,
            nursingRequirement:'',
            orderNo:'',
            price:'',
            unit:'',
            image:''
    } 
}

const ruleFormRef=ref(null)
const rules = ref({
  nursingRequirement: [
    { required: true, message: '请输入护理要求', trigger: 'blur' },
  ],
  name: [
    { required: true, message: '请输入护理名称', trigger: 'blur' },
  ],
  orderNo: [
    { required: true, message: '请选排序号', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' },
  ],
   status: [
    { required: true, message: '请选择状态', trigger: 'blur' },
  ],
   unit: [
    { required: true, message: '请输入单位', trigger: 'blur' },
  ]
});

  //提交表单校验
const addEmp=async()=>{
   if (!ruleFormRef) return
  await ruleFormRef.value.validate(async (valid, fields) => {
    let result = null
    if (valid) {
      //远程调用
      //根据formData的id判断是否为空，是新增还是修改，id不为空则是修改
      if(formData.value.id){
        //修改
        result = await updateProject(formData.value)
      }else{
        //新增
        result = await addProject(formData.value)
      }
    //判断结果
    //刷新并关闭弹窗
    if(result.code){
      dialogShow.value=false
      handleSearch()
      //提示
      ElMessage.success('操作成功！')
    }else{
      ElMessage.error('操作失败')
    }

    
    
    }
    else {
      console.log('提交失败!', fields)
    } 
    

  })
}
  const handleAvatarSuccess = (
    response,   
    uploadFile
  ) => {
    // 将预览图片换成响应的图片
    formData.value.image =response.data
  }
   // 文件上传前调用的方法：beforeAvatarUpload
  const beforeAvatarUpload= (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
      ElMessage.error('图片格式必须是JPG格式!')
      return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
      ElMessage.error('图片最大大小是2MB!')
      return false
    }
    return true
  }


  //回显
  const handleEdit = async (id) =>{
    console.log('Edit',id)
    const result = await queryById(id)
    formData.value = result.data
      //弹窗
  dialogShow.value = true
  }


  const token = ref({token:''})
const getToken = () =>{
  let userInfo =localStorage.getItem('userInfo')
  if(userInfo){
    token.value.token = JSON.parse(userInfo).token
  }
}

onMounted(()=>{
  handleSearch()
  getToken()
})


</script>



<template>
<el-dialog  v-model="dialogShow"
    :title="tips"
    width="800"
    :before-close="handleClose">
>
  <span>是否删除这条数据</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit()">
          确认
        </el-button>
      </div>
    </template>
</el-dialog>
<el-dialog     
    v-model="dialogShow"
    :title="tips"
    width="800"
    :before-close="handleClose">

    <el-form
        ref="ruleFormRef"
        style="max-width: 800px"
        :model="formData"
        :rules="rules"
        label-width="auto">

        <el-row :gutter="0">
            <el-col :span="24">
                <el-form-item label="护理名称" prop="name">
                    <el-input v-model="formData.name" placeholder="请输入员工姓名"/>
                </el-form-item>
            </el-col>  
            <el-col :span="24">
                <el-form-item label="护理要求" prop="nursingRequirement">
                    <el-input v-model="formData.nursingRequirement" placeholder="请输入员工姓名"/>
                </el-form-item>
            </el-col>  
            <el-col :span="24">
                <el-form-item label="排序号" prop="orderNo">
                    <el-input v-model="formData.orderNo" placeholder="请输入员工姓名"/>
                </el-form-item>
            </el-col>  
            <el-col :span="24">
                <el-form-item label="价格" prop="price">
                    <el-input v-model="formData.price" placeholder="请输入员工姓名"/>
                </el-form-item>
            </el-col>  
            <el-col :span="24">
                <el-form-item label="状态" prop="status">
                    <el-select v-model="formData.status" placeholder="请输入员工姓名">
                        <el-option v-for="(status,index) in statusList" :key="index" :label="status.name" :value="status.value"/>
                    </el-select>
                </el-form-item>
            </el-col>  
            <el-col :span="24">
                <el-form-item label="单位" prop="unit">
                    <el-input v-model="formData.unit" placeholder="请输入员工姓名"/>
                </el-form-item>
            </el-col>  

          <!-- 用户头像上传 -->
          <el-col :span="24">
              <el-form-item label="头像" prop="image">
                <el-upload
                  class="avatar-uploader"
                  action="/api/upload"
                  :headers="token"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                >
                <!-- 为什么不需要写value -->
                  <img v-if="formData.image" :src="formData.image" class="avatar" />
                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
              </el-form-item>
          </el-col>
        </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogShow = false">取消</el-button>
        <el-button type="primary" @click="addEmp">
          确认
        </el-button>
      </div>
    </template>
</el-dialog>



  <h1>护理模块</h1>
 <el-form :inline="true" :model="searchService" >
    <el-form-item label="姓名">
      <el-input v-model="searchService.name" placeholder="请输入员工姓名"/>
    </el-form-item>
    <el-form-item label="状态">
      <el-select v-model="searchService.status" placeholder="请选择">
        <el-option label="可用" value="1" />
        <el-option label="不可用" value="2" />
      </el-select>
    </el-form-item>

     <el-form-item>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button >清空</el-button>
    </el-form-item>
  </el-form>

<el-button type="primary" @click="showDialog">添加员工</el-button>
<el-button type="danger" @click="deleteByIds">批量删除</el-button>


<div class="pdbox">
    <el-table :data="serviceList"  @selection-change="handleSelectionChange" style="width: 100%">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="主键ID" />
        <el-table-column prop="name" label="姓名"  />
        <el-table-column prop="orderNo" label="排序号"  />
        <el-table-column prop="unit" label="单位"  />
        <el-table-column prop="price" label="排序号"  />
          <el-table-column prop="status" label="状态"  >
                <template #default="scope">
                    {{ scope.row.status==1?'可用':'不可用' }}       
                </template>
          </el-table-column>
        <el-table-column prop="nursingRequirement" label="护理要求"/>
        <el-table-column prop="image" label="头像" >
                <template #default="scope">
                <el-image :src="scope.row.image" width="100" height="100" />
                </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间"  />
        <el-table-column prop="updateTime" label="更新时间"  />
        <el-table-column prop="createBy" label="创建人"  />
            <el-table-column fixed="right" label="操作" min-width="120">
                <template #default="scope">
                    <el-button type="primary" size="small" @click="handleEdit(scope.row.id)">编辑</el-button>
                    <el-button type="danger" size="small" @click="deleteById(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
    </el-table>

</div>

    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 15, 20]"
      :size="size"
      :disabled="disabled"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
</template>



<style>

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

</style>